import React, { useRef } from 'react';
import PropTypes from 'prop-types';
import { Form, Input, message, Select, Typography } from 'antd';
import { useRequest } from '@/hooks';
import useDictionary from '@/hooks/useDictionary';
import FormContainer from './FormContainer';

const { Option } = Select;
const { Text } = Typography;

/**
 * 员工档案 - 紧急联系人
 */
const EmergencyContactSection = ({ formData, onChange, readonly, saveAction, ...props }) => {
    const formRef = useRef();
    // 提交
    const { run: submitRun } = useRequest(submitData => saveAction && saveAction(submitData), {
        manual: true
    });
    // 字典数据
    const [emergencyRelationshipList, getEmergencyRelationshipText] = useDictionary('emergencyRelationship');

    // 保存
    const handleSubmit = async values => {
        const submitData = Object.assign({
            entryPersonnelCode: formData.entryPersonnelCode,
            emergencyContact: values.emergencyContact,
            emergencyRelationship: values.emergencyRelationship,
            emergencyTelephone: values.emergencyTelephone,
            emergencyAreaCode: values.emergencyAreaCode
        });
        // 提交
        const res = await submitRun(submitData);
        if (res.code === 10000) {
            message.success(res.msg);
            onChange(submitData);
        } else {
            message.error(res.msg);
        }
    };

    // render
    return (
        <FormContainer
            ref={formRef}
            title="紧急联系人"
            hasEditAuth={!readonly && !!saveAction}
            onSubmit={handleSubmit}
            {...props}
        >
            {({ getFieldDecorator }, editStatus) => (
                <>
                    <Form.Item label="姓名">
                        {editStatus ? (
                            getFieldDecorator('emergencyContact', {
                                initialValue: formData.emergencyContact || undefined,
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入紧急联系人姓名'
                                    },
                                    {
                                        min: 2,
                                        max: 50,
                                        message: '请输入2~50个字符'
                                    },
                                    {
                                        pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                        message: '此处不能输入空格'
                                    }
                                ]
                            })(<Input placeholder="请输入紧急联系人姓名" />)
                        ) : (
                            <div className="multiLineText">{formData.emergencyContact || '--'}</div>
                        )}
                    </Form.Item>
                    <Form.Item label="与本人关系">
                        {editStatus ? (
                            getFieldDecorator('emergencyRelationship', {
                                initialValue: formData?.emergencyRelationship || undefined,
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择与本人关系'
                                    }
                                ]
                            })(
                                <Select
                                    placeholder="请选择与本人关系"
                                    getPopupContainer={trigger => trigger.parentElement}
                                >
                                    {emergencyRelationshipList?.map(item => (
                                        <Option value={item.value} key={item.value}>
                                            {item.text}
                                        </Option>
                                    ))}
                                </Select>
                            )
                        ) : (
                            <Text>
                                {formData?.emergencyRelationship
                                    ? getEmergencyRelationshipText(formData?.emergencyRelationship)
                                    : '--'}
                            </Text>
                        )}
                    </Form.Item>
                    <Form.Item label="手机号码">
                        {editStatus ? (
                            getFieldDecorator('emergencyTelephone', {
                                initialValue: formData.emergencyTelephone || undefined,
                                rules: [
                                    {
                                        required: true,
                                        validator(rule, value, callback) {
                                            const regex = /^\d{7,11}$/;
                                            if (!value) {
                                                callback('手机号不能为空');
                                            } else if (!regex.test(value)) {
                                                callback('只能输入7-11位数字');
                                            }
                                            callback();
                                        }
                                    }
                                ]
                            })(
                                <Input
                                    placeholder="请填入手机号"
                                    addonBefore={getFieldDecorator('emergencyAreaCode', {
                                        initialValue: formData.emergencyAreaCode || '86'
                                    })(
                                        <Select
                                            getPopupContainer={trigger => trigger.parentElement}
                                            placeholder="区号"
                                            style={{ width: 80 }}
                                        >
                                            <Option value="86">+86</Option>
                                            <Option value="65">+65</Option>
                                        </Select>
                                    )}
                                />
                            )
                        ) : (
                            <Text>
                                {formData.emergencyTelephone
                                    ? `${formData?.emergencyAreaCode ? `+${formData.emergencyAreaCode}` : ''} ${
                                          formData.emergencyTelephone
                                      }`
                                    : '--'}
                            </Text>
                        )}
                    </Form.Item>
                </>
            )}
        </FormContainer>
    );
};

// prop
EmergencyContactSection.propTypes = {
    formData: PropTypes.object.isRequired,
    onChange: PropTypes.func.isRequired,
    saveAction: PropTypes.func,
    readonly: PropTypes.bool
};

EmergencyContactSection.defaultProps = {
    saveAction: null,
    readonly: false
};

export default EmergencyContactSection;
